package homework10package;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * serial_class
 * 
 * this class provides functions that makes serializing Serializables easy.
 * 
 * @author Orion Taylor
 * @course Software Engineering
 * @date 4-1-13
 */

public class serial_class {
	
	/** function serialize
	 * 
	 * this function takes in a Serializable object as input
	 * and outputs the byte array representation of said object
	 * 
	 * @param my_ser: the Serializable object we want to serialize
	 * @return byte[]: the serialization of the object
	 */
	public byte[] serialize(Serializable my_ser) throws IOException,
	ClassNotFoundException{
		
		//This is really all boilerplate stuff. No one cares
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		 ObjectOutput out = null;
		 byte[] yourBytes = null;
		 try {
		   out = new ObjectOutputStream(bos);   
		   out.writeObject(my_ser);
		   yourBytes = bos.toByteArray();

		 } finally {
		   out.close();
		   bos.close();
		 }
		 
		 return yourBytes;
	}
	
	/** function deserialize
	 * 
	 * this function takes in a byte array representation of a 
	 * serialized object and oupts the corresponding Object.
	 * 
	 * @param yourBytes: the serializtion of the object we care about
	 * @return Object: the object we want deserialized
	 */
	public  Object deserialize(byte[] yourBytes) throws IOException,
	ClassNotFoundException{
		
		//This is really all boilerplate stuff. No one cares
		
		 ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
		 ObjectInput in = null;
		 Object o = null;
		 try {
		   in = new ObjectInputStream(bis);
		   o = (Serializable) in.readObject();
		 } finally {
		   bis.close();
		   in.close();
		 }
		 
		 return o;
		
	}

}
